<template>
  <div class="content-wrapper">
    <div class="content-header">
      <el-page-header
        v-if="!this.$route.query.location"
        :content="this.$route.query.repositoryName"
        @back="goBack"
      />
      <el-page-header
        v-if="this.$route.query.location"
        :content="this.$route.query.location"
        @back="goBack"
      />
      <el-breadcrumb
        style="margin-top: 10px"
        separator-class="el-icon-arrow-right"
      >
        <el-breadcrumb-item
          v-for="(item, index) of brandList"
          :key="index"
          @click.native="breadsClick(item)"
        >
          <span
            v-if="index == 0"
            style="cursor: pointer"
            @click.stop="doThis"
            @click="backtrack(index)"
            >{{ repositoryName }} <i class="el-icon-arrow-right classi" />
          </span>
          <span style="cursor: pointer">{{ item.name }}</span>
        </el-breadcrumb-item>
      </el-breadcrumb>
    </div>
    <div class="content-container">
      <div v-if="belongTo" class="filter-container">
        <el-dropdown v-if="newPermission" trigger="click" class="filter-item">
          <el-button type="primary" size="mini" round
            >新建<i class="el-icon-circle-plus el-icon--right button-icon"
          /></el-button>
          <el-dropdown-menu slot="dropdown" class="user-dropdown">
            <el-dropdown-item @click.native="createDocument(1)">
              <svg class="icon" aria-hidden="true">
                <use xlink:href="#el-icon-alldocx" />
              </svg>
              新建文档
            </el-dropdown-item>
            <el-dropdown-item @click.native="createDocument(2)">
              <svg class="icon" aria-hidden="true">
                <use xlink:href="#el-icon-allxlsx" /></svg
              >新建表格
            </el-dropdown-item>
            <el-dropdown-item @click.native="createDocument(3)">
              <svg class="icon" aria-hidden="true">
                <use xlink:href="#el-icon-allpptx" />
              </svg>
              新建演示稿
            </el-dropdown-item>
            <el-dropdown-item divided @click.native="createFolder">
              <svg class="icon" aria-hidden="true">
                <use xlink:href="#el-icon-allweibiaoti-_huabanfuben" />
              </svg>
              新建文件夹
            </el-dropdown-item>
            <el-dropdown-item divided @click.native="openRecordDialog">
              <svg class="icon" aria-hidden="true">
                <use xlink:href="#el-icon-allweibiaoti-_huabanfuben" />
              </svg>
              新建记录
            </el-dropdown-item>
          </el-dropdown-menu>
        </el-dropdown>
        <el-dropdown v-if="newPermission" trigger="click" class="filter-item">
          <el-button size="mini" round
            >上传<i class="el-icon-upload2 el-icon--right button-icon"
          /></el-button>
          <el-dropdown-menu slot="dropdown" class="user-dropdown">
            <el-dropdown-item>
              <div @click="uploading()">
                <i class="el-icon-document document-icon" />
                上传文件
              </div>
            </el-dropdown-item>
            <el-dropdown-item>
              <i class="el-icon-folder folder-icon" />
              上传文件夹
            </el-dropdown-item>
          </el-dropdown-menu>
        </el-dropdown>
        <el-dropdown v-if="movePermission" class="filter-item" trigger="click">
          <el-dropdown-menu />
          <el-button size="mini" round @click.native="toDirectoryLayout"
            >目录编排<i class="el-icon-sort el-icon--right button-icon"
          /></el-button>
        </el-dropdown>
      </div>
      <!-- <div class="filter-container" /> -->
      <!-- v-if="multipleSelection.length > 0"  -->
      <div class="filter-container">
        <span class="filter-item filter-item-label">批量操作 </span>
        <el-button
          v-if="deletePermission && belongTo"
          size="mini"
          round
          class="filter-item"
          @click="batchDelete"
          >删除<i
            class="el-icon-delete el-icon--right button-icon danger-color"
        /></el-button>
        <el-button
          v-if="downloadPermission"
          size="mini"
          round
          class="filter-item"
          @click="batchDownload"
          >下载<i
            class="el-icon-download el-icon--right button-icon blue-color"
        /></el-button>
      </div>
      <el-scrollbar>
        <div>
          <el-table
            v-if="list"
            ref="tableData"
            v-loading="listLoading"
            class="tabel"
            height="650"
            :data="
              list.filter(
                (data) =>
                  !search ||
                  data.documentName.toLowerCase().includes(search.toLowerCase())
              )
            "
            highlight-current-row
            style="width: 100%"
            :default-sort="{ prop: 'date', order: 'descending' }"
            @selection-change="handleSelectionChange"
          >
            <!-- :selectable="selectable" -->
            <el-table-column
              type="selection"
              :selectable="selectable"
              width="55"
              fixed
            />
            <el-table-column label="名称"  min-width="200">
              <template slot-scope="scope">
                <span
                  v-if="scope.row.folderName"
                  style="cursor: pointer"
                  @click="childFile(scope.row)"
                  ><svg class="icon" aria-hidden="true">
                    <use
                      :xlink:href="iconType(scope.row.fileExtension).class"
                    />
                  </svg>
                  {{ scope.row.folderName }}</span
                >
                <span v-if="scope.row.documentName"
                  ><svg class="icon" aria-hidden="true">
                    <use
                      :xlink:href="iconType(scope.row.fileExtension).class"
                    /></svg
                  >{{ scope.row.documentName }}{{ scope.row.fileExtension }}
                </span>
              </template>
                      <template slot="header" slot-scope="scope">
                <el-input
                  v-model="search"
                  size="mini"
                  placeholder="输入关键字搜索"
                />
              </template>
            </el-table-column>

            <el-table-column
              label="创建人"
              sortable
              prop="createdName"
              width="150px"
            />
            <el-table-column
              sortable
              label="最近使用时间"
              prop="accessTimeString"
              width="200px"
              align="center"
            />
            <el-table-column label="大小" sortable prop="size" width="100px" />
            <el-table-column
              label="操作"
              align="center"
              width="120px"
              fixed="right"
            >
              <template slot-scope="scope">
                <el-row v-if="belongTo">
                  <el-col :span="12">
                    <el-tooltip content="点击取消收藏" placement="top">
                      <el-button
                        v-if="
                          scope.row.documentName && scope.row.documentFavoriteId
                        "
                        type="text"
                        class="el-icon-star-on button-icon"
                        @click="deletedCollect(scope.row)"
                      />
                    </el-tooltip>
                    <el-tooltip content="点击收藏" placement="top">
                      <el-button
                        v-if="
                          scope.row.documentName &&
                          !scope.row.documentFavoriteId
                        "
                        type="text"
                        class="el-icon-star-off button-icon"
                        @click="collectDocument(scope.row)"
                      />
                    </el-tooltip>
                    <span v-if="scope.row.folderName"><i /></span>
                  </el-col>
                  <el-col :span="12">
                    <el-dropdown trigger="click" class="filter-item">
                      <el-button type="text" class="el-icon-more" />
                      <el-dropdown-menu slot="dropdown" class="user-dropdown">
                        <el-dropdown-item
                          v-if="
                            scope.row.documentName &&
                            previewPermission &&
                            scope.row.documentType == 1
                          "
                          @click.native="viewDocument(scope.row, 'view')"
                          >预览</el-dropdown-item
                        >
                        <el-dropdown-item
                          v-if="
                            scope.row.documentName &&
                            previewPermission &&
                            scope.row.documentType == 4
                          "
                          @click.native="pdfView(scope.row, 'view')"
                          >预览pdf</el-dropdown-item
                        >
                        <el-dropdown-item
                          v-if="
                            scope.row.documentName &&
                            editPermission &&
                            !scope.row.documentFlowLock &&
                            scope.row.documentType != 4
                          "
                          @click.native="viewDocument(scope.row, 'edit')"
                          >编辑</el-dropdown-item
                        >
                        <el-dropdown-item
                          v-if="roles[0] == 'qa'"
                          @click.native="viewDocument(scope.row, 'edit')"
                          >编辑(违规){{ roles }}</el-dropdown-item
                        >
                        <el-dropdown-item
                          v-if="scope.row.documentName && printPermission"
                          @click.native="viewDocument(scope.row)"
                          >打印</el-dropdown-item
                        >
                        <el-dropdown-item
                          v-if="
                            scope.row.documentName &&
                            renamePermission &&
                            !scope.row.documentFlowLock
                          "
                          divided
                          @click.native="renameDocuemnt(scope.row)"
                          >重命名</el-dropdown-item
                        >
                        <el-dropdown-item
                          v-if="scope.row.folderName && renamePermission"
                          @click.native="renameFolder(scope.row)"
                          >重命名</el-dropdown-item
                        >
                        <el-dropdown-item
                          v-if="scope.row.documentName && sharePermission"
                          @click.native="openShare(scope.row, 0)"
                          >分享
                        </el-dropdown-item>
                        <!-- <el-dropdown-item
                          v-if="scope.row.folderName && sharePermission"
                          @click.native="openShare(scope.row, 1)"
                          >分享
                        </el-dropdown-item> -->
                        <el-dropdown-item
                          v-if="scope.row.documentName && sharePermission"
                          @click.native="relevance(scope.row)"
                          >关联</el-dropdown-item
                        >
                        <el-dropdown-item
                          v-if="copyPermission"
                          divided
                          @click.native="copyAt(scope.row)"
                          >复制到当前</el-dropdown-item
                        >
                        <el-dropdown-item
                          v-if="copyPermission"
                          divided
                          @click.native="copy(scope.row)"
                          >复制...</el-dropdown-item
                        >
                        <el-dropdown-item
                          v-if="movePermission"
                          @click.native="move(scope.row)"
                          >移动</el-dropdown-item
                        >
                        <el-dropdown-item
                          v-if="scope.row.documentId && downloadPermission"
                          @click.native="fileDownload(scope.row)"
                          >下载</el-dropdown-item
                        >
                        <el-dropdown-item
                          v-if="scope.row.folderName && deletePermission"
                          divided
                          @click.native="oneDelete(scope.row, 1)"
                          >删除</el-dropdown-item
                        >
                        <el-dropdown-item
                          v-if="
                            scope.row.documentName &&
                            deletePermission &&
                            !scope.row.documentFlowLock
                          "
                          divided
                          @click.native="oneDelete(scope.row, 0)"
                          >删除</el-dropdown-item
                        >
                        <el-dropdown-item
                          divided
                          @click.native="oneProperty(scope.row)"
                          >属性</el-dropdown-item
                        >
                      </el-dropdown-menu>
                    </el-dropdown>
                  </el-col>
                </el-row>

                <el-row v-if="!belongTo">
                  <el-col :span="12">
                    <el-dropdown
                      v-if="scope.row.documentName"
                      trigger="click"
                      class="filter-item"
                    >
                      <el-button type="text" class="el-icon-more" />
                      <el-dropdown-menu slot="dropdown" class="user-dropdown">
                        <el-dropdown-item
                          v-if="
                            scope.row.documentName &&
                            previewPermission &&
                            scope.row.documentType !== 4
                          "
                          @click.native="viewDocument(scope.row, 'view')"
                          >预览</el-dropdown-item
                        >
                        <el-dropdown-item
                          v-if="
                            scope.row.documentName &&
                            previewPermission &&
                            scope.row.documentType == 4
                          "
                          @click.native="pdfView(scope.row, 'view')"
                          >预览pdf</el-dropdown-item
                        >
                        <!-- <el-dropdown-item
                          v-if="
                            roles[0] == 'qa' &&
                              scope.row.documentName &&
                              previewPermission &&
                              scope.row.documentType !== 4
                          "
                          @click.native="viewDocument(scope.row, 'edit')"
                        >编辑(违规){{ roles }}</el-dropdown-item> -->
                        <el-dropdown-item
                          v-if="scope.row.documentId && downloadPermission"
                          @click.native="fileDownload(scope.row)"
                          >下载</el-dropdown-item
                        >
                      </el-dropdown-menu>
                    </el-dropdown>
                  </el-col>
                </el-row>
              </template>
            </el-table-column>
          </el-table>
        </div>
      </el-scrollbar>

      <UploadFile :uploadingdata="uploadingdata" />
    </div>
    <!-- 分享框 -->
    <el-dialog
      title="分享选择"
      :visible.sync="dialogVisibles"
      class="small"
      @close="closeShare"
    >
      <el-row>
        <el-col style="text-align: right" :span="5"> 分享目标类型： </el-col>
        <el-col :offset="1" :span="5">
          <el-radio
            v-model="saveShare.shareTargetType"
            :label="0"
            @change="shareTargetTypeChange"
            >人员</el-radio
          >
        </el-col>
        <el-col :span="5">
          <el-radio
            v-model="saveShare.shareTargetType"
            :label="1"
            @change="shareTargetTypeChange"
            >团队</el-radio
          >
        </el-col>
      </el-row>

      <el-row style="margin-top: 20px">
        <el-col style="text-align: right" :span="5"> 分享目标： </el-col>
        <el-col v-if="saveShare.shareTargetType == 0" :offset="1" :span="18">
          <selectPersonnelTree
            :personnel-data="personnelData"
            :review.sync="reviewAndUserGroup"
          />
        </el-col>
        <el-col v-else :offset="1" :span="18">
          <selectUserGroupTree
            :user-group-data="UserGroupData"
            :review.sync="reviewAndUserGroup"
          />
        </el-col>
      </el-row>

      <el-row style="margin-top: 20px">
        <el-col style="text-align: right" :span="5"> 选择分享方式： </el-col>
        <el-col :offset="1" :span="6">
          <el-radio-group v-model="saveShare.status" @change="statusChange">
            <div class="radio">
              <el-radio :label="1">永久</el-radio>
              <el-radio :label="2">选择分享到期时间</el-radio>
            </div>

            <el-date-picker
              v-if="this.saveShare.status == 2"
              v-model="saveShare.deadline"
              value-format="yyyy-MM-dd HH:mm:ss"
              type="datetime"
              placeholder="选择日期"
              style="margin-top: 20px"
            />
          </el-radio-group>
        </el-col>
      </el-row>

      <el-row style="margin-top: 20px">
        <el-col style="text-align: right" :span="5"> 权限： </el-col>
        <el-col :offset="1" :span="6">
          <el-checkbox
            v-model="permissions"
            label="4"
            @change="permissionChange"
            >下载</el-checkbox
          >
          <el-checkbox
            v-model="permissions"
            label="2"
            @change="permissionChange"
            >打印</el-checkbox
          >
        </el-col>
      </el-row>

      <!-- 分割 -->
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisibles = false">取 消</el-button>
        <el-button type="primary" @click="saveSharer()">确 定</el-button>
      </span>
    </el-dialog>

    <el-dialog
      title="目录编排"
      :visible.sync="dialogVisible"
      class="small"
      @close="getList"
    />
    <!--关系视图-->
    <el-dialog
      :visible.sync="relationView"
      class="normal"
      :modal="true"
      @close="closeRelation"
    >
      <RelationView :document-id="documentId" :document-name="documentName" />
    </el-dialog>

    <!--创建记录-->
    <el-dialog
      title="新建记录"
      :visible.sync="recordVisible"
      width="30%"
      @close="recordClose"
    >
      <el-form ref="form" :model="recordForm" label-width="80px">
        <el-form-item label="选择文件">
          <el-select
            v-model="recordForm.documentId"
            filterable
            placeholder="请选择"
          >
            <el-option
              v-for="(item, index) in documentList"
              :key="item.value"
              :label="item.documentName"
              :value="item.documentId"
            />
          </el-select>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="recordVisible = false">取 消</el-button>
        <el-button type="primary" @click="recordData">确 定</el-button>
      </span>
    </el-dialog>
    <Property :property-data="PropertyData" />
    <DeleteTips
      :delete-tips-data="DeleteTipsData"
      @pushDeleteTipsData="pushDeleteTipsData"
    />
    <Copy :copy-data="CopyData" />
    <Move :move-data="MoveData" />
    <Relevance :relevance-data="RelevanceData" />
  </div>
</template>

<script>
import {
  listFolder,
  saveFolder,
  deleteFolder,
  updateNameFolder,
  copyFolder
} from '@/api/fd/folder'
import {
  deleteDocument,
  updateDocument,
  createDocument,
  deleteByIds,
  copy,
  downloadFile
} from '@/api/fd/document'
import { saveDocumentFavorite, deleteDocumentFavorite } from '@/api/xd/favorite'
import { get, set } from '@/utils/db.js'
import { getsearch, getBranchList } from '@/api/uc/search'
import { save } from '@/api/xd/share_to'
import { unity } from '@/styles/js/setIconType.js'

import RelationView from '@/views/document/file/relationView'
import UploadFile from '@/components/UploadFile/index'
import selectPersonnelTree from '@/components/SelectPersonnel/selectPersonnelTree'
import selectUserGroupTree from '@/components/SelectUserGroup/selectUserGroupTree'
import Property from '@/views/document/components/Property'
import DeleteTips from '@/components/DeleteTips/index'
import Copy from '@/components/Copy/index'
import Move from '@/components/Move/index'
import Relevance from '@/components/Relevance/index'
import permissionList from '@/utils/permissionList.js'
import { getDocumentListByType } from '@/api/xd/documentFlow'
import { mapGetters } from 'vuex'

export default {
  inject: ['reload'],
  components: {
    File,
    RelationView,
    UploadFile,
    selectPersonnelTree,
    selectUserGroupTree,
    Property,
    DeleteTips,
    Copy,
    Move,
    Relevance
  },
  data() {
    return {
      iconType: unity.setIconType,
      documentName: null,
      multipleSelection: [],
      list: null,
      total: 0,
      listLoading: true,
      temp: {
        parentFolderId: null,
        folderName: null,
        folderId: null,
        repositoryId: null
      },
      brandList: [],
      brands: [],
      repositoryName: '',
      dialogVisible: false,
      data: [],
      dialogVisibles: false,
      uploadings: false,
      uploadingdata: '',
      documentId: null, // 需要分享的文档id
      saveShare: {
        // 分享保存数据
        shareId: null, // 分享Id
        shareType: 1, // 分享类型：0-文档，1-文件夹，2-知识库
        shareTargetIdList: [], // 分享目标用户Id
        shareTargetType: 0, // 分享目标类型：0-用户，1-部门
        permission: 0,
        status: 1, // 分享选择的状态
        deadline: null // 如果有限制日期则选择日期
      },
      dialogRelation: false, // 关联对话框
      relationDocumentId: null,
      relationView: false, // 关联视图接口
      reviewAndUserGroup: null, // 用于接收子组件传递过来的数据信息，部门或者或者人员
      permissions: [],
      deleteData: {
        folderIds: [],
        documentIds: []
      },
      // 属性
      PropertyData: {},
      // 删除提示
      DeleteTipsData: {},
      confirm: false,
      // 复制，移动
      CopyData: '',
      // 是否管理员
      apply: '',

      MoveData: '',
      RelevanceData: '',
      UserGroupData: '',
      personnelData: '',
      repositoryPermissio: null,
      copyPermission: false, // 权限
      movePermission: false,
      downloadPermission: false,
      TeamAdmin: '',
      editPermission: '',
      sharePermission: '',
      deletePermission: '',
      printPermission: '',
      renamePermission: '',
      previewPermission: '',
      newPermission: '',
      // 记录文件新增部分
      recordVisible: false,
      documentList: [],
      recordForm: {
        documentId: ''
      },
      batchType: '',
      a: 0,
      search: '',
      belongTo: ''
    }
  },
  computed: {
    ...mapGetters(['roles'])
  },
  watch: {
    $route() {
      this.$router.go(0)
    },
    batchType(data) {}
  },
  beforeUpdate() {
    if (this.$route.query.row.permission) {
      console.log(this.$route.query.row, 'this.$route.query.row')
      set('repositoryPermissio', this.$route.query.row.permission)
      set('belongTo', this.$route.query.row.belongTo)
    }
  },
  mounted() {
    this.getList()
    this.getBread()
    this.getBranchList()
    this.getSearch()
    if (this.$route.query.row.permission) {
      set('repositoryPermissio', this.$route.query.row.permission)
      set('belongTo', JSON.stringify(this.$route.query.row.belongTo))
    }
    this.repositoryPermissio = JSON.parse(get('repositoryPermissio'))
    this.isBelongTo(JSON.parse(get('belongTo')))
    // 管理员
    this.TeamAdmin = JSON.parse(get('TeamAdmin'))

    // 下载
    this.downloadPermission =
      this.TeamAdmin ||
      (permissionList.DOWNLOAD & this.repositoryPermissio) ==
        permissionList.DOWNLOAD
    // 移动
    this.movePermission =
      this.TeamAdmin ||
      (permissionList.MOVE & this.repositoryPermissio) == permissionList.MOVE
    // 复制
    this.copyPermission =
      this.TeamAdmin ||
      (permissionList.COPY & this.repositoryPermissio) == permissionList.COPY
    // 删除
    this.deletePermission =
      this.TeamAdmin ||
      (permissionList.DELETE & this.repositoryPermissio) ==
        permissionList.DELETE
    // 打印
    this.printPermission =
      this.TeamAdmin ||
      (permissionList.PRINT & this.repositoryPermissio) == permissionList.PRINT
    // 分享
    this.sharePermission =
      this.TeamAdmin ||
      (permissionList.SHARE & this.repositoryPermissio) == permissionList.SHARE
    // 关联
    this.associatePermission =
      this.TeamAdmin ||
      (permissionList.ASSOCIATE & this.repositoryPermissio) ==
        permissionList.ASSOCIATE
    // 编辑
    this.editPermission =
      this.TeamAdmin ||
      (permissionList.EDIT & this.repositoryPermissio) == permissionList.EDIT
    // 重命名
    this.renamePermission =
      this.TeamAdmin ||
      (permissionList.RENAME & this.repositoryPermissio) ==
        permissionList.RENAME
    // 预览
    this.previewPermission =
      this.TeamAdmin ||
      (permissionList.PREVIEW & this.repositoryPermissio) ==
        permissionList.PREVIEW
    // 新增
    this.newPermission =
      this.TeamAdmin ||
      (permissionList.NEW & this.repositoryPermissio) == permissionList.NEW
  },

  methods: {
    isBelongTo(data) {
      let row = false
      if (data == 0) {
        row = false
      } else {
        row = true
      }
      this.belongTo = row
    },
    dateFormat(fmt, date) {
      let ret
      const opt = {
        'Y+': date.getFullYear().toString(), // 年
        'm+': (date.getMonth() + 1).toString(), // 月
        'd+': date.getDate().toString(), // 日
        'H+': date.getHours().toString(), // 时
        'M+': date.getMinutes().toString(), // 分
        'S+': date.getSeconds().toString() // 秒
        // 有其他格式化字符需求可以继续添加，必须转化成字符串
      }
      for (const k in opt) {
        ret = new RegExp('(' + k + ')').exec(fmt)
        if (ret) {
          fmt = fmt.replace(
            ret[1],
            ret[1].length == 1 ? opt[k] : opt[k].padStart(ret[1].length, '0')
          )
        }
      }
      return fmt
    },
    /**
     * 保存记录创建数据
     */
    recordData() {
      if (!this.recordForm.documentId) {
        this.$message.warning('未选择文件')
        return
      }

      const date = this.dateFormat('YYYY-mm-dd HH:MM', new Date())
      this.recordForm.documentName = '记录文件' + date
      this.getList()
      copy(this.recordForm).then((res) => {
        this.recordVisible = false
        this.getList()
        window.open(
          'onlyoffice/createDocument.html?&token=' +
            this.$store.getters.token +
            '&documentId=' +
            res.data.documentId +
            '&mode=edit' +
            '&urldata=' +
            process.env.VUE_APP_BASE_API
        )
      })
    },
    /**
     * 打开创建记录对话框
     */
    openRecordDialog() {
      this.recordVisible = true
      this.recordForm.destRepositoryId = this.temp.repositoryId
      this.recordForm.destFolderId = this.temp.parentFolderId
        ? this.temp.parentFolderId
        : 0
      if (!this.documentList || this.documentList.length == 0) {
        getDocumentListByType({ type: 'JL' }).then((res) => {
          this.documentList = res.data
        })
      }
    },
    /**
     * 新增记录
     */
    recordClose() {
      this.recordForm = {
        documentId: ''
      }
    },
    permissionChange() {
      // 分享多选权限时触发
      let permission = 0

      if (this.permissions.length > 0) {
        this.permissions.forEach((item) => {
          permission += parseInt(item)
        })
      }
      this.saveShare.permission = permission
    },
    shareTargetTypeChange(val) {
      // 分享单选分享目标类型时触发
      this.saveShare.shareTargetType = val
    },
    // 返回上一页
    goBack() {
      // goBacks()
      this.$router.go(-1)
    },
    // 返回
    backtrack(index) {
      console.log(index, 'index')
      this.temp.parentFolderId = ''
      this.getList()
      this.getBread()
    },
    openRelationView(row) {
      this.documentId = row.documentId
      this.documentName = row.documentName
      this.relationView = true
    },
    doThis() {},
    closeRelation() {
      this.documentId = null
    },
    relevance(row) {
      // 打开关联对话框
      this.RelevanceData = {
        deleteDialog: true,
        title: '关联文件',
        row: row
      }
    },
    statusChange(val) {
      if (val == 1) {
        this.saveShare.deadline = null
      }
    },
    saveSharer() {
      // 定义分享目标
      this.saveShare.shareTargetIdList = this.reviewAndUserGroup.map((item) => {
        return item.id
      })
      if (this.saveShare.shareTargetIdList) {
        // return;
      }

      // 判断时间是否存在
      if (this.saveShare.status == 2) {
        if (!this.saveShare.deadline) {
          this.$message.info('到期时间不可为空')
          return
        }
      }
      this.saveShare.repositoryId = this.temp.repositoryId
      save(this.saveShare).then((res) => {
        this.$message.success('分享成功')
        this.dialogVisibles = false
        this.saveShare.status = 1
      })
    },
    // 上传参数repositoryId, folderId
    uploading() {
      const repositoryId = this.temp.repositoryId
      const folderId = this.temp.parentFolderId
      this.uploadings = true
      this.uploadingdata = {
        uploadings: true,
        repositoryId: this.temp.repositoryId,
        folderId: this.temp.parentFolderId
      }
    },
    renameFolder(row) {
      this.$prompt('输入文件夹名称', '提示', {
        inputValue: row.folderName,
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        inputValidator: (res) => {
          if (res == null || res.trim() == '') {
            return '文件名称不可为空'
          }
          return true
        }
      })
        .then(({ value }) => {
          var param = {
            folderId: row.folderId,
            folderName: value
          }
          updateNameFolder(param).then((res) => {
            this.$message.success('修改成功')
            this.getList()
          })
        })
        .catch(() => {
          this.$message.info('取消输入')
        })
    },
    renameDocuemnt(row) {
      this.$prompt('输入文件名称', '提示', {
        inputValue: row.documentName,
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        inputValidator: (res) => {
          if (res == null || res.trim() == '') {
            return '文件名称不可为空'
          }
          return true
        }
      })
        .then(({ value }) => {
          var param = {
            documentId: row.documentId,
            documentName: value
          }
          updateDocument(param).then((res) => {
            this.$message.success('修改成功')
            this.getList()
          })
        })
        .catch(() => {
          this.$message.info('取消输入')
        })
    },
    toDirectoryLayout() {
      this.$router.push('/document/directoryLayout/' + this.temp.repositoryId)
    },
    deletedCollect(row) {
      deleteDocumentFavorite({
        documentFavoriteId: row.documentFavoriteId
      }).then((res) => {
        if (res.code === 1) {
          this.$message.success('已取消收藏')
          this.getList()
        }
      })
    },
    collectDocument(row) {
      saveDocumentFavorite({ documentId: row.documentId }).then((res) => {
        if (res.code === 1) {
          this.$message.success('收藏成功，可在收藏文件中查看')
          this.getList()
        } else {
          this.$message.error('收藏失败')
        }
      })
    },
    breadsClick(item, index) {
      this.breads = JSON.parse(localStorage.getItem('breadList'))
      var flag = true
      for (var i = this.breads.length - 1; i >= 0; i--) {
        if (this.breads[i].parentFolderId === item.parentFolderId) {
          flag = false
        }
        if (flag) {
          this.breads.splice(i, 1)
        }
      }
      localStorage.setItem('breadList', JSON.stringify(this.breads))
      this.temp.parentFolderId = item.parentFolderId
      this.getList()
      this.getBread()
    },
    getBread() {
      var breads = localStorage.getItem('breadList')
      if (breads !== 'undefined') {
        this.brandList = JSON.parse(breads)
      } else {
        localStorage.setItem('breadList', '[]')
      }
      if (!this.temp.parentFolderId) {
        this.brandList = []
        localStorage.setItem('breadList', '[]')
      }
    },
    oneDelete(row, type) {
      this.DeleteTipsData = {
        deleteDialog: true,
        type: type,
        row: row,
        title: '删除'
      }
    },
    pushDeleteTipsData(val) {
      if (val.type == 1) {
        deleteFolder({ folderId: val.row.folderId }).then((res) => {
          if (res.code === 1) {
            this.$message.success('删除成功')
            this.getList()
          }
        })
      } else if (val.type == 0) {
        deleteDocument({ documentId: val.row.documentId }).then((res) => {
          if (res.code === 1) {
            this.$message.success('删除成功')
            this.getList()
          }
        })
      } else if (val.type == 2) {
        deleteByIds(this.deleteData).then((res) => {
          if (res.code == 1) {
            this.deleteData = {
              folderIds: [],
              documentIds: []
            }
            this.$message.success('删除成功')
            this.getList()
          }
        })
      }
    },
    // 批量删除
    batchDelete() {
      this.batchType = 0
      this.deleteData.folderIds = []
      this.deleteData.documentIds = []
      console.log(this.batchType, 'this.multipleSelection')
      if (this.multipleSelection.length <= 0) {
        this.$message.warning('请选择删除文件')
      } else {
        this.multipleSelection.forEach((res) => {
          if (res.folderId != 0 && !res.documentId) {
            this.deleteData.folderIds.push(res.folderId)
          } else {
            this.deleteData.documentIds.push(res.documentId)
          }
        })
        this.DeleteTipsData = {
          deleteDialog: true,
          type: 2,
          row: this.deleteData,
          title: '删除'
        }
      }
    },
    createDocument(val) {
      this.$prompt('请输入文档名称', '新建', {
        confirmButtonText: '确定',
        cancelButtonText: '取消'
      })
        .then(({ value }) => {
          var data = {
            documentType: val,
            folderId: this.temp.parentFolderId ? this.temp.parentFolderId : 0,
            repositoryId: this.temp.repositoryId,
            documentName: value,
            documentFlowLock: false
          }
          createDocument(data).then((res) => {
            if (res.data != null) {
              this.getList()
              window.open(
                'onlyoffice/createDocument.html?&token=' +
                  this.$store.getters.token +
                  '&documentId=' +
                  res.data.documentId +
                  '&mode=edit' +
                  '&urldata=' +
                  process.env.VUE_APP_BASE_API
              )
            } else {
              this.$message.error('创建失败')
            }
          })
        })
        .catch(() => {
          this.$message({
            type: 'info',
            message: '取消创建'
          })
        })
    },
    createFolder() {
      this.$prompt('新建文件夹名称', '新建', {
        confirmButtonText: '确定',
        cancelButtonText: '取消'
      })
        .then(({ value }) => {
          var data = {
            repositoryId: this.temp.repositoryId,
            parentFolderId: this.temp.parentFolderId
              ? this.temp.parentFolderId
              : 0,
            folderName: value
          }
          saveFolder(data).then((res) => {
            if (res.code === 1) {
              this.$message.success('创建成功')
              this.getList()
            }
          })
        })
        .catch(() => {
          this.$message({
            type: 'info',
            message: '取消创建'
          })
        })
    },
    childFile(row) {
      var path = {
        name: row.folderName,
        path: '/document/file/' + row.repositoryId,
        parentFolderId: row.folderId
      }
      this.breads = JSON.parse(localStorage.getItem('breadList'))
      this.breads.push(path)
      localStorage.setItem('breadList', JSON.stringify(this.breads))
      this.temp.repositoryId = row.repositoryId
      this.temp.parentFolderId = row.folderId
      this.getList()
      this.getBread()
    },
    updateDocument(row) {
      window.open(
        'onlyoffice/createDocument.html?&token=' +
          this.$store.getters.token +
          '&documentId=' +
          row.documentId +
          '&mode=edit' +
          '&urldata=' +
          process.env.VUE_APP_BASE_API
      )
    },
    handleSelectionChange(val) {
      this.multipleSelection = val
    },
    // 禁用
    selectable(row) {
      // if (this.batchType === 0 || row.documentId) {
      //   if (!row.documentFlowLock) {
      //     return true
      //   } else {
      //     return false
      //   }
      // } else {
      //   return true
      // }
      return true
    },
    getList() {
      this.temp.repositoryId = this.$route.params.repositoryId
      if (this.$route.query.row.shareId) {
        this.temp.folderId = this.$route.query.row.shareId
      }
      // 分享收藏进入id
      if (this.$route.query.row.shareId) {
        this.temp.parentFolderId = this.$route.query.row.shareId
      }
      if (this.$route.query.parentFolderId) {
        this.temp.parentFolderId = this.$route.query.parentFolderId
      }
      listFolder(this.temp).then((res) => {
        if (res.code === 1) {
          this.list = res.data
          this.listLoading = false
        }
      })
      if (this.$route.query.repositoryName) {
        this.repositoryName = this.$route.query.repositoryName
      }
    },
    viewDocument(row, mode) {
      window.open(
        'onlyoffice/createDocument.html?&token=' +
          this.$store.getters.token +
          '&documentId=' +
          row.documentId +
          '&mode=' +
          mode +
          '&urldata=' +
          process.env.VUE_APP_BASE_API
      )
    },
    pdfView(row, mode) {
      window.open(
        process.env.VUE_APP_BASE_API +
          '/api/fd/pdf/get_document_by_pdf?documentId=' +
          row.documentId
      )
    },
    // 分享
    async openShare(row, type) {
      this.saveShare.shareType = type
      if (type == 0) {
        this.saveShare.shareId = row.documentId
      } else {
        this.saveShare.shareId = row.folderId
      }

      this.dialogVisibles = true
    },
    // 分享
    closeShare() {
      this.saveShare.status = 1
    },

    // 打开属性页面
    oneProperty(row) {
      this.PropertyData = {
        dialogVisible: true,
        dataList: row
      }
    },
    // 下载功能
    fileDownload(row) {
      downloadFile({
        documentId: row.documentId
      }).then((res) => {
        const { url, documentName } = res.data
        this.getBlob(url).then((blob) => {
          this.saveAs(blob, documentName)
        })
      })
    },
    // 下载重命名
    getBlob(url) {
      return new Promise((resolve) => {
        const xhr = new XMLHttpRequest()

        xhr.open('GET', url, true)
        xhr.responseType = 'blob'
        xhr.setRequestHeader(
          'Content-Type',
          'application/x-www-form-urlencoded'
        )
        xhr.send('user=admin')
        xhr.onload = () => {
          if (xhr.readyState === 4 && xhr.status === 200) {
            resolve(xhr.response)
          }
        }

        // xhr.send()
      })
    },
    // 下载重命名
    saveAs(blob, filename) {
      if (window.navigator.msSaveOrOpenBlob) {
        navigator.msSaveBlob(blob, filename)
      } else {
        const link = document.createElement('a')
        const body = document.querySelector('body')
        link.href = window.URL.createObjectURL(blob)
        link.download = filename
        link.style.display = 'none'
        body.appendChild(link)
        link.click()
        body.removeChild(link)
        window.URL.revokeObjectURL(link.href)
        this.a = this.a + 1
        console.log(this.a)
      }
    },
    // 复制
    copy(row) {
      let title = '复制文件夹'
      if (row.documentId) {
        title = '复制文件'
      }
      this.CopyData = {
        deleteDialog: true,
        title: title,
        row: row
      }
    },
    move(row) {
      let title = '移动文件夹'
      if (row.documentId) {
        title = '移动文件'
      }
      this.MoveData = {
        deleteDialog: true,
        title: title,
        row: row
      }
    },
    // 复制到当前
    copyAt(row) {
      if (row.documentId) {
        const data = {
          destFolderId: row.folderId,
          destRepositoryId: row.repositoryId,
          documentId: row.documentId
        }
        copy(data).then((res) => {
          if (res.code === 1) {
            this.$message.success('复制文件成功')
            this.value = ''
            this.treeData = ''
            this.getList()
          }
        })
      } else {
        const data = {
          folderId: row.folderId,
          folderName: row.folderName,
          parentFolderId: row.parentFolderId,
          repositoryId: row.repositoryId
        }
        copyFolder(data).then((res) => {
          if (res.code === 1) {
            this.$message.success('复制文件夹成功')
            this.value = ''
            this.treeData = ''
            this.getList()
          }
        })
      }
    },
    // 分享树数据
    // 获取数据
    async getSearch() {
      const data = await getsearch()
      this.personnelData = data.data.groupUserTree
      this.UserGroupData = data.data.teamUserTree
    },
    async getBranchList() {
      const data = await getBranchList()
      const reviewData = data.data.teamUserTree

      // 添加团队数据11111111111111111111111
      this.UserGroupData = reviewData
    },

    // 批量下载
    batchDownload() {
      this.batchType = 1
      if (this.multipleSelection.length > 0) {
        for (let i = 0; i < this.multipleSelection.length; i++) {
          ;((t, data) => {
            setTimeout(() => {
              this.fileDownload(data)
            }, 1000 * t) // 每秒执行一次
          })(i, this.multipleSelection[i])
        }
      } else {
        this.$message.warning('请选择下载文件')
      }
    }
  }
}
</script>

<style lang="scss" scoped>
.dialogbox {
  margin-top: 50px;
}
.el-breadcrumb {
  margin: 18px 0px 18px 10px;
  font-size: 13px;
}
.classi {
  padding-right: 5px;
}
.radio {
  display: flex;
  justify-content: center;
  align-items: center;
}
</style>
